package com.gaoxin.api.contronller.syscontroller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gaoxin.api.entity.ConfigEntity;
import com.gaoxin.api.service.sysservice.QueryStuUserService;
import com.gaoxin.api.util.ImUrlEnum;
import com.gaoxin.api.util.SignUtil;

@RestController
@RequestMapping("app/sys")
public class ImController {

	@Autowired
	private ConfigEntity configEntity;
	@Autowired
	private QueryStuUserService queryStuUserService;

	@RequestMapping("/labelinfo")
	public String imService(@RequestBody String params) {
		String jsonData = null;
		JSONObject data = JSONObject.parseObject(params);
		Object reqData = checkData(data);
		if (reqData instanceof String) {
			return makeRetFail((String) reqData);
		}
		String phone = data.getJSONObject("data").getString("phone");

		Map<String, Object> retMap = new HashMap<String, Object>();

		try {
			String queryUserLable = queryStuUserService.queryUserLable(phone);
			retMap.put("phone", phone);
			retMap.put("label", queryUserLable);
			jsonData = JSON.toJSONString(retMap);
		} catch (Exception e) {
			e.printStackTrace();
			retMap.put("code", "100102");
			retMap.put("errmsg", "无法查询到对应的导员信息！");
			jsonData = JSON.toJSONString(retMap);
		}
		return jsonData;

	}

	private String getReqUrl(JSONObject data) {
		return ImUrlEnum.getUrlByCode(data.getString("type"));
	}

	private String makeRetFail(String msg) {
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("retCode", "FAIL");
		retMap.put("retMsg", msg);
		return JSON.toJSONString(retMap);
	}

	private Object checkData(JSONObject data) {
		String channelid = data.getString("channelid");
		if (StringUtils.isBlank(channelid)) {
			return "request params[channelid] error.";
		}
		String sign = data.getString("sign");
		if (StringUtils.isBlank(sign)) {
			return "request params[sign] error.";
		}
		String reqdata = data.getString("data");
		if (StringUtils.isBlank(reqdata)) {
			return "request params[data] error.";
		}
		JSONObject reqDataObject = JSON.parseObject(reqdata);
		// 验证签名数据
		boolean verifyFlag = SignUtil.verifyPaySign(reqDataObject, sign, configEntity.getSecret());
		if (!verifyFlag) {
			return "Verify sign failed.";
		}
		return reqDataObject;
	}
}
